package Threadsx;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 薛剑
 * @date 2020-11-23 9:36
 */

class ShareDat{

    private   int num=0;
    private   int unms=0;
    private Lock lock = new ReentrantLock();
    private Condition conditiones = lock.newCondition();


    public  void  increnum() {

        try {
            lock.lock();
            while (num != 0) {
               conditiones.await();
            }
            num++;


            System.out.println("num加一执行"+num+Thread.currentThread().getName());
            System.out.println();
            conditiones.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
    //自减函数


    public void descnum() throws InterruptedException {

        TimeUnit.SECONDS.sleep(1);

        try {
            lock.lock();
            while (num == 0) {
                conditiones.await();
            }
            num--;
            System.out.println("num自减执行"+num+Thread.currentThread().getName());
            System.out.println();
            conditiones.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }


}
public class TestCustomer {



    public static void main(String[] args) {
          ShareDat shareDat = new ShareDat();
          new Thread(()->{

              for (int i = 0; i <5 ; i++) {
                          shareDat.increnum();         
              }


          },"AA").start();
          //线程B
        new Thread(()->{
            for (int i = 0; i <5 ; i++) {
                try {
                    shareDat.descnum();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        },"BB").start();

        new Thread(()->{

            for (int i = 0; i < 5; i++) {
                shareDat.increnum();
            }


        },"CC").start();




         new Thread(()->{

           for (int i = 0; i < 5; i++   )    {
               try {
                   shareDat.descnum();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }


         },"DD").start();


}
}